
// ===============================================================================================================
// -*- C++ -*-
//
// OpenGL.cpp - Common OpenGL related code used by the application.
//
// Copyright (c) 2011 Guilherme R. Lampert
// guilherme.ronaldo.lampert@gmail.com
//
// This code is licenced under the MIT license.
//
// This software is provided "as is" without express or implied
// warranties. You may freely copy and compile this source into
// applications you distribute provided that the copyright text
// above is included in the resulting source code.
//
// ===============================================================================================================

#include <Common.hpp>
#include <OpenGL.hpp>

GLboolean glInitExtensions(void)
{
	if (glewInit() == GLEW_OK)
	{
		if ((GLEW_ARB_vertex_shader) && (GLEW_ARB_fragment_shader)
		&& (GLEW_ARB_vertex_array_object) && (GLEW_EXT_compiled_vertex_array))
		{
			return (GL_TRUE);
		}
	}

	return (GL_FALSE);
}

void glBegin2D(GLint windowWidth, GLint windowHeight)
{
	glMatrixMode(GL_PROJECTION);
	glPushMatrix();

	glLoadIdentity();

	// Set 2D projection:
	glOrtho(0.0, static_cast<double>(windowWidth), static_cast<double>(windowHeight), 0.0, -1.0, 1.0);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	// Prepare OpenGL to draw sprites with alpha:
	glPushAttrib(GL_ALL_ATTRIB_BITS);

	glDisable(GL_TEXTURE_2D);
	glEnable(GL_COLOR_MATERIAL);

	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glEnable(GL_ALPHA_TEST);
	glAlphaFunc(GL_GREATER, 0);
}

void glEnd2D(void)
{
	glPopAttrib();

	glMatrixMode(GL_PROJECTION);
	glPopMatrix();
	glMatrixMode(GL_MODELVIEW);
}

GLint glPrintf(GLint x, GLint y, const char * format, ...)
{
	char buffer[2048];
	va_list vaList;
	GLint nCount, i;

	va_start(vaList, format);
	nCount = vsnprintf(buffer, sizeof(buffer), format, vaList);
	va_end(vaList);

	glRasterPos2i(x, y);

	for (i = 0; i < nCount; ++i)
	{
		glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, buffer[i]);
	}

	return (nCount);
}